import { round } from 'lodash';
import { ElMessageBox, dayjs, messageType } from 'element-plus';
import { messageUtil } from '@jl/element-plus/utils';
import html2canvas from 'html2canvas';

// 计算图层层级
export const getLayerMaxIndex = (data: API.Scene.ILayer[]) => {
  // const indexArr: number[] = [];
  // data.forEach((item: API.Scene.ILayer) => {
  //   indexArr.push(item.zIndex);
  // });
  // indexArr.sort((a: number, b: number) => b - a);
  // if (!indexArr.length) {
  //   return 1;
  // }
  // return indexArr[0] + 1;
  return 1;
};

// 文件大小转Mb
export function transferMb(size: number) {
  return round(size / 1024 / 1024, 2);
}

// 二次确认
export const confirmAgain = (
  title: string,
  content: string,
  confirmButtonText?: string,
  cancelButtonText?: string,
  customClass?: string
) => {
  return new Promise((resolve: any) => {
    ElMessageBox.confirm(
      `<div class='title'>${title}

      </div>
    <div class='sub-title'>${content}</div>`,
      '',
      {
        confirmButtonText: confirmButtonText || '确定',
        cancelButtonText: cancelButtonText || '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        customClass: customClass || '',
      }
    )
      .then(() => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

// alert确认
export const messageAlert = (title: string, content: string, type: messageType) => {
  return new Promise((resolve: any) => {
    ElMessageBox.alert(
      `<div class='title'>${title}

      </div>
    <div class='sub-title'>${content}</div>`,
      '',
      {
        confirmButtonText: '我知道了',
        type: type ?? 'success',
        dangerouslyUseHTMLString: true,
        showClose: false,
      }
    )
      .then(() => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

// 资源路径
export function retFilePath(path: string) {
  if (!path) return '';
  let result = path;
  if (result.indexOf('gis/') === 0) {
    result = result.substring(4);
  } else if (result.indexOf('play/') === 0) {
    result = result.substring(5);
  }

  result = '/res/' + result;
  return result;
}

// 复制
export function copyText(value: string, tip = true) {
  if (!value) return null;
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.setAttribute('value', value);
  input.select();
  const result = document.execCommand('copy');
  document.body.removeChild(input);
  if (tip) {
    messageUtil.success('复制成功');
  }
  return result;
}

export function calcExpirationTime(expirationTime: string) {
  if (expirationTime) {
    if (expirationTime === '2030-01-01 00:00:00') {
      return { name: '永久有效', code: 1 };
    }
    const date1 = dayjs();
    const date2 = dayjs(expirationTime);
    const diffDay = date2.diff(date1, 'day');
    const diffHour = date2.diff(date1, 'hour');
    if (diffHour <= 0) {
      return { name: '已过期', code: 3 };
    }
    if (diffDay > 0) {
      return { name: `${diffDay + 1}天后`, code: 2 };
    }
    return { name: `${diffHour + 1}小时后`, code: 2 };
  }
  return { name: '已过期', code: 3 };
}

export function judgeIsDevelop() {
  return process.env.NODE_ENV === 'development';
}

export function notNumberInRange(number: number, min: number, max: number) {
  return !(number >= min && number <= max);
}
/**
 * @name:利用html2canvas插件把DOM节点截图成为图片
 * @param {DOM} DOM 需要截图的DOM节点 document.getElementById('box');
 * @param {string} fileName 生成截图的名称 例如：'thumbnail.jpg'
 * @param {number} ratio 图片压缩率（0.1-1）
 */
export function myHtml2canvas(
  DOM: HTMLElement,
  fileName = `base64${Math.random().toString().split('.')}.jpg`,
  ratio = 0.5
) {
  return new Promise((resolve) => {
    html2canvas(DOM).then(function (canvas: any) {
      const dataURL = canvas.toDataURL('image/jpeg', ratio);
      const arr = dataURL.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const blob = new Blob([u8arr], { type: mime });
      const file = new window.File([blob], fileName, {
        type: 'image/jpeg',
      });
      resolve(file);
    });
  });
}

/**
 * 生成随机字符串
 * @returns
 */
export function randomString() {
  const timestamp = new Date().getTime().toString(36); // 转换时间戳为36进制字符串
  const randomPart = Math.random().toString(36).substr(2, 5); // 随机数的一部分
  const uniqueString = timestamp + randomPart;

  return uniqueString;
}

/**
 * 平铺数组转树结构
 * @param flatArray
 * @param props
 * @returns
 */
export function createTreeFromFlatArray(
  flatArray: any[],
  props = {
    parentId: 'parentId',
    id: 'id',
  }
) {
  const tree: any[] = [];
  const getChildren = (flatArray: any[], tree: any[], parentId: '') => {
    for (const item of flatArray) {
      if (item[props.parentId] === parentId) {
        const newItem = { children: [], ...item };
        tree.push(newItem);
        getChildren(flatArray, newItem.children, item[props.id]);
      }
    }
  };
  getChildren(flatArray, tree, '');
  return tree;
}

/**
 * 树结构转树
 * @param root
 * @returns []
 */
export function flattenTreeIterative(root: any[]) {
  const result = [];
  const stack = root || [];

  while (stack.length > 0) {
    const node = stack.pop();
    const { children, ...data } = node;
    result.push(data);

    if (node.children) {
      for (let i = node.children.length - 1; i >= 0; i--) {
        stack.push(node.children[i]);
      }
    }
  }

  return result;
}

/**
 * 设置排序字段
 * @param root
 */
export function setTreeSortField(root: any[]) {
  root.forEach((v: any, i: number) => {
    v.fe_order = i;
    if (v.children?.length > 0) {
      setTreeSortField(v.children);
    }
  });
}

/**
 *
 * @param root 树结构排序
 */
export function sortTreeData(root: any[]) {
  root.sort((a, b) => a.fe_order - b.fe_order);
  root.forEach((node: any) => {
    if (node.children?.length > 0) {
      sortTreeData(node.children);
    }
  });
}

export function deleteTreeNode(
  root: any[],
  id: string,
  props = {
    id: 'id',
  }
) {
  const deleteNode = (root: any[]) => {
    root.forEach((node: any, index: number) => {
      if (node[props.id] === id) {
        root.splice(index, 1);
        console.log('xxxxxx删除成功', node);
      }
      if (node.children?.length > 0) {
        deleteNode(node.children);
      }
    });
  };
  deleteNode(root);
}

/**
 * 图层树找节点
 */
export function getNodeByTree(layerName: string, data: any[]) {
  for (const list of data) {
    if (list.code && list.layerName === layerName) {
      return list;
    } else if (list.type === 'folder' && list.children && list.children.length) {
      getNodeByTree(layerName, list.children);
    }
  }
}

/**
 * 查找树形结构某个节点所有子节点
 * @param list 树形结构扁平化数组
 * @param parent 节点id
 * @returns
 */
export function getChildren(list: any[], parent: string) {
  let result: string[] = [];

  for (const item of list) {
    if (item.parent === parent) {
      result.push(item.id);
      const children = getChildren(list, item.id);
      result = result.concat(children);
    }
  }

  return result;
}

/**
 *
 * @param str 目标字符串
 * @returns
 */
export function isJSON(str: string) {
  if (typeof str !== 'string') {
    // 1、传入值必须是 字符串
    // console.log('It is not a string! [' + str + ']');
    return false;
  }
  try {
    const obj = JSON.parse(str); // 2、仅仅通过 JSON.parse(str)，不能完全检验一个字符串是JSON格式的字符串
    if (typeof obj === 'object' && obj) {
      // 3、还必须是 object 类型
      return true;
    } else {
      return false;
    }
  } catch (e) {
    return false;
  }
}

/**
 * 根绝url获取fileName
 * @param url
 * @returns
 */
export function getFileNameByUrl(url: string) {
  const index = url.lastIndexOf('/') + 1;
  return url.substring(index).split('.')[0];
}
